import React, { Component } from 'react'
import Taro from '@tarojs/taro'
import {View, ScrollView, Image, Text, Picker } from '@tarojs/components'
import {AtSwipeAction, AtInputNumber, AtButton} from 'taro-ui'
import { Decimal } from 'decimal.js'

import './index.scss'
import '../Iconfont/iconfont.css'

import {URL} from "../../utils/request";


export default class Index extends Component {
  state={
    empty: false,
    carts_goods: [],
    order_goods: [],
    order_sum: 0,
    checkAllStatus: false,
  }

  componentDidMount() {
    this.setNavBar();
    this.getServ();
  }

  componentDidUpdate () {
    this.setNavBar();
  }

  setNavBar () {
    Taro.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#ffffff'
    });

    Taro.setNavigationBarTitle({
      title: '购物车'
    });
  }

  getServ () {
    let cartsData = Taro.getStorageSync('carts');

    if(cartsData === '' || cartsData === null || typeof cartsData === 'undefined') {
      this.setState({ empty: true });
    } else {
      cartsData = JSON.parse(cartsData);

      let goods_ids = cartsData.map(item => item.goods_id);

      Taro.request({
        method: 'POST',
        url: `${URL}api/goods_lists`,
        data: {
          goods_ids: JSON.stringify(goods_ids)
        },
        header: {
          'content-type': 'application/json' // 默认值
        }
      }).then(res => {
        let data = res.data.data;
        let serv = {};

        if(Object.prototype.toString.call(data) === '[object Object]') {
          data = Object.getOwnPropertyNames(data).map((k) => {
            return data[k];
          });
        }

        data&&data.map(item => {
          serv[item.goods_id] = item;
        });

        cartsData = cartsData&&cartsData.map(item => {
          item['picture'] = serv[item.goods_id]['pictures'][0];
          item['name'] = serv[item.goods_id]['name'];
          item['price'] = serv[item.goods_id]['price'];
          return item;
        });

        this.setState({ carts_goods: cartsData });
      });

    }
  }

  uniqueGoods(goods) {
    return `${goods.goods_id}${goods.goods_model}${goods.goods_style}`;
  }

  number (goods, number) {
    let cartsData = Taro.getStorageSync('carts');
    cartsData = JSON.parse(cartsData);

    let { carts_goods, order_goods } = this.state;

    cartsData = cartsData.map((item) => {
      if(this.uniqueGoods(item) === this.uniqueGoods(goods)) {
        item.goods_number = number;
      }
      return item;
    });
    carts_goods = carts_goods.map((item) => {
      if(this.uniqueGoods(item) === this.uniqueGoods(goods)) {
        item.goods_number = number;
      }
      return item;
    });

    if(order_goods.length > 0) {
      order_goods = order_goods.map((item) => {
        if(this.uniqueGoods(item) === this.uniqueGoods(goods)) {
          item.goods_number = number;
        }
        return item;
      });

      this.setOrderSum(order_goods);

      this.setState({ order_goods });
    }

    this.setState({ carts_goods });
    Taro.setStorageSync('carts', JSON.stringify(cartsData));
  }

  handleConfirm(e, willDelete) {
    if(e.key === 1) {
      let cartsData = Taro.getStorageSync('carts');
      cartsData = JSON.parse(cartsData);
      let { carts_goods, order_goods } = this.state;

      cartsData = cartsData.filter((item) => {
        return this.uniqueGoods(item) !== this.uniqueGoods(willDelete);
      });
      carts_goods = carts_goods.filter((item) => {
        return this.uniqueGoods(item) !== this.uniqueGoods(willDelete);
      });

      if(order_goods.length > 0) {
        order_goods = order_goods.filter((item) => {
          return this.uniqueGoods(item) !== this.uniqueGoods(willDelete);
        });
        order_goods = Object.values(order_goods);
        this.setOrderSum(order_goods);
        this.setState({ order_goods });
      }

      this.setState({ carts_goods: Object.values(carts_goods) });
      Taro.setStorageSync('carts', JSON.stringify(Object.values(cartsData)));
    }
  }

  checkBoxStyle(item) {
    const { order_goods } = this.state;

    let ids = order_goods.map(val => this.uniqueGoods(val));
    return ids.includes(this.uniqueGoods(item)) ? 'iconfont icon-checked checked-style' : 'iconfont icon-unchecked unchecked-style';
  }

  setOrderSum (order_goods) {
    let order_sum = 0;
    if(order_goods.length > 0) {
      order_sum = order_goods.map(val => Decimal.mul(val.goods_number, val.price).toNumber()).reduce((prev, curr) => Decimal.add(prev, curr).toNumber());
    }
    this.setState({ order_sum: (new Decimal(order_sum)).toFixed(2) });
  }

  checkBox(item) {
    let { order_goods, carts_goods } = this.state;

    let ids = order_goods.map(val => this.uniqueGoods(val));

    if(ids.includes(this.uniqueGoods(item))) {
      order_goods = order_goods.filter(val => this.uniqueGoods(val) !== this.uniqueGoods(item));
      order_goods = Object.values(order_goods);
    } else {
      order_goods.push(item);
    }

    this.setOrderSum (order_goods);

    this.setState({
      order_goods: [...order_goods],
      checkAllStatus: (order_goods.length === carts_goods.length)
    });
  }

  checkAll() {
    let { checkAllStatus, carts_goods } = this.state;
    checkAllStatus = !checkAllStatus;
    let order_goods = [];
    if(checkAllStatus) {
      order_goods = [...carts_goods];
    }

    this.setOrderSum(order_goods);
    this.setState({ checkAllStatus, order_goods });
  }

  checkAllStyle() {
    return this.state.checkAllStatus ? 'iconfont icon-checked checked-style' : 'iconfont icon-unchecked unchecked-style';
  }

  goodsDetail(goods) {
    Taro.navigateTo({url: `/pages/goods_detail/index?goods_id=${goods.goods_id}`});
  }

  placeOrder() {
    const { order_goods } = this.state;
    if(order_goods.length <= 0) {

      Taro.showToast({
        title: '请勾选商品购买',
        icon: 'none',
        duration: 2000
      });

      return;
    }
  }

  render () {
    const { empty, carts_goods, order_sum } = this.state;

    return empty ? <View>
      <Text> 没有内容 </Text>
    </View> : <View>
      <ScrollView
        scrollY
        scrollWithAnimation
        className='carts-box'
      >
        {carts_goods&&carts_goods.map((item, index) => <AtSwipeAction
          key={index}
          className='carts-at-swipe-action'
          onClick={(e) => this.handleConfirm(e, item)}
          autoClose
          options={[
            {
              key: 0,
              text: '取消',
              style: {
                backgroundColor: '#E0E0E0'
              }
            },
            {
              key: 1,
              text: '删除',
              style: {
                backgroundColor: '#E62C6F'
              }
            }
          ]}
        >
          <View className='carts-goods-list'>
            <View style='width: 26px; line-height: 100px;' onClick={() => this.checkBox(item)}>
              <Text className={this.checkBoxStyle(item)} style='font-size: 20px;' />
            </View>
            <View style='width: 100px; height: 100px; margin-right: 10px;' onClick={() => this.goodsDetail(item)}>
              <Image src={item.picture} style='width: 100px; height: 100px;' />
            </View>
            <View>
              <View className='carts-goods-list-name'>{item.name}</View>
              <View className='carts-goods-list-price'>￥{Decimal.mul(item.price, item.goods_number).toFixed(2)}</View>
              <View className='carts-goods-list-attr'>
                <View style='display: flex; justify-content: left;'>
                  <View className='model-style-btn-clicked' >{item.goods_model}</View>
                  <View className='model-style-btn-clicked' >{item.goods_style}</View>
                </View>
                <AtInputNumber
                  min={1}
                  max={10}
                  step={1}
                  value={item.goods_number}
                  onChange={(e) => this.number(item, e)}
                  type='number'
                />
              </View>
            </View>
          </View>
        </AtSwipeAction>)}
      </ScrollView>

      <View className='carts-top-btn'>
        <View style='width: 32px; line-height: 60px; text-align: right;' onClick={() => this.checkAll()} >
          <Text className={this.checkAllStyle()} style='font-size: 20px;' />
        </View>
        <View>总共：<Text style='color: #E62C6F;'>￥{(new Decimal(order_sum)).toFixed(2)}元</Text></View>
        <View style='width: 150px; margin-top: 14px;'>
          <AtButton
            type='secondary'
            size='small'
            onClick={() => this.placeOrder()}
          >
            立即下单
          </AtButton>
        </View>

      </View>
    </View>;
  }
}

